package com.wxtbk.service;

import java.sql.Timestamp;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javen.utils.WeiXinUtils;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.wxtbk.model.WtWxuser;
import com.wxtbk.model.WtWxuserFrom;


public class WeixinService {
	static Log logger = Log.getLog(WeixinService.class);

	public void saveWeixinUser(String openId, String sceneid) {
		// 1,保存用户推荐人信息
		WtWxuser user = WtWxuser.dao.findByOpenId(openId);
		if (user == null) {			
			
			ApiResult apiResult = com.jfinal.weixin.sdk.api.UserApi.getUserInfo(openId);
			if (apiResult.isSucceed()) {
				int subscribe = 0;
				JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
				String nickName = jsonObject.getString("nickname");
				// 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex = jsonObject.getIntValue("sex");
				String city = jsonObject.getString("city");// 城市
				String province = jsonObject.getString("province");// 省份
				String country = jsonObject.getString("country");// 国家
				String headimgurl = jsonObject.getString("headimgurl");
				String unionid = jsonObject.getString("unionid");
				// 获取用户信息判断是否关注
				ApiResult userInfo = UserApi.getUserInfo(openId);
				logger.warn(JsonKit.toJson("is subsribe>>" + userInfo));
				if (userInfo.isSucceed()) {
					String userStr = userInfo.toString();
					subscribe = JSON.parseObject(userStr).getIntValue("subscribe");
				}

				WtWxuser.dao.save(openId, WeiXinUtils.filterWeixinEmoji(nickName), unionid, headimgurl, country, city,
						province, sex);
			}
			if (sceneid != null) {
				WtWxuserFrom userfrom = new WtWxuserFrom();
				userfrom.setOpenId(openId);
				userfrom.setFromSceneId(Integer.parseInt(sceneid));
				Date now = new Date();
				userfrom.setCreateTime(now);
				userfrom.save();

			}

		}
	}
}
